﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using IService;
using Model;
using System.Threading.Tasks;
using Service;
using WMS.Models;
using DAL;

namespace WMS.Controllers
{
    /// <summary>
    /// 出库管理页面
    /// </summary>
    public class WhOutboundController : Controller
    {
        /// <summary>
        /// 出库
        /// </summary>
        private readonly IWhOutboundService _iwos;
        /// <summary>
        /// 出库明细
        /// </summary>
        private readonly IWhOutboundDetailService _iwods;
        /// <summary>
        /// 缓存
        /// </summary>
        private readonly IDictService _ids;
        /// <summary>
        /// 编号规则
        /// </summary>
        private readonly INumberingRuleService _inbrs;
        /// <summary>
        /// 销售订单
        /// </summary>
        private readonly IOmSalesOrderService _iosos;
        private readonly AppDbContext _dbContext;
        public WhOutboundController(IWhOutboundService iwos, IWhOutboundDetailService iwods, IDictService ids, INumberingRuleService inbrs, IOmSalesOrderService iosos, AppDbContext context)
        {
            _iwos = iwos;
            _iwods = iwods;
            _ids = ids;
            _inbrs = inbrs;
            _iosos = iosos;
            _dbContext = context;
        }

        /// <summary>
        /// 主页面
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Index()
        {
            return View();
        }

        /// <summary>
        /// 获取所有出库单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            var result = await _iwos.GetWhOutboundAll();
            if (result.Count == 0)
            {
                return this.Error();
            }
            return this.Success(result);
        }

        /// <summary>
        /// 根据查询条件获取出库单数据
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetByParams([FromBody] StockOutQueryParams parameters)
        {
            var result = await _iwos.GetWhOutboundByParams(parameters);
            return Ok(new { code = 200, data = new { result = result, total = result.Count } });
        }

        /// <summary>
        /// 根据ID获取出库单详情
        /// </summary>
        /// <param name="id">出库单ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetById(long id)
        {
            var result = await _iwos.GetWhOutboundId(id);
            return Json(new { code = 200, data = result });
        }

        /// <summary>
        /// 根据出库单ID获取明细项
        /// </summary>
        /// <param name="stockOutOrderId">出库单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetDetailsByOrderId(long stockOutOrderId)
        {
            var result = await _iwods.GetDetailsByOrderId(stockOutOrderId);
            return Json(new { code = 200, data = result });
        }
        // 在控制器外部或内部定义这个类
        public class DictDataResult
        {
            public List<DictItem> OutboundTypes { get; set; }
            public List<DictItem> StatusList { get; set; }
        }

        public class DictItem
        {
            public string label { get; set; }
            public string value { get; set; }
        }
        /// <summary>
        /// 获取出库类型和状态的字典数据
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetDictData()
        {
            List<WmsDictData> typeList = new List<WmsDictData>();
            List<WmsDictData> statusList = new List<WmsDictData>();
            // 出库类型
            var dictType = await _ids.GetDictTypeAsync("sys_stockout_type");
            if (dictType != null)
            {
                typeList = await _ids.GetDictDataListAsync(dictType.DictTypeId);

            }
            // 出库状态
            var status = await _ids.GetDictTypeAsync("sys_order_statu");
            if (status != null)
            {
                statusList = await _ids.GetDictDataListAsync(status.DictTypeId);
            }
            var result = new
            {
                OutboundTypes = typeList.Select(x => new
                {
                    label = x.Code,
                    value = x.Name,
                }).ToList(),
                StatusList = statusList.Select(x => new
                {
                    label = x.Code,
                    value = x.Name
                }).ToList()
            };
            return this.Success(result);
        }
        /// <summary>
        /// 详细信息页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(int id, string pwd)
        {
            return View();
        }

        /// <summary>
        /// 详细信息页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Details(int id)
        {
            return Ok();
        }

        /// <summary>
        /// 添加页面
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Create()
        {
            return View();
        }

        // POST: WhOutboundController/Create
        [HttpPost]
        public ActionResult Create(IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        /// <summary>
        /// 创建出库单（包含明细）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateOutbound([FromBody] CreateOutboundRequest request)
        {
            try
            {
                // 生成出库单号
                request.Outbound.StockOutOrderNo = await _inbrs.GenerateAndUpdateNumberAsync(3);

                var result = await _iwos.CreateOutboundWithDetailsAsync(request.Outbound, request.Details);
                if (result > 0)
                {
                    return this.Success("出库单创建成功");
                }
                else
                {
                    return this.Error();
                }
            }
            catch (Exception ex)
            {
                return this.Error("错误:"+ ex);
            }
        }

        /// <summary>
        /// 根据销售订单和仓库获取可出库货品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetAvailableGoodsBySalesOrder(string salesOrderNo, long warehouseId)
        {
            // 首先获取所有可出库货品
            var result = await _iwos.GetAvailableGoodsBySalesOrder(salesOrderNo);

            if (result != null)
            {
                // 根据仓库ID过滤货品
                var filteredResult = result.Where(x => x.WarehouseId == warehouseId).ToList();
                return this.Success(filteredResult);
            }
            else
            {
                return this.Error();
            }
        }

        /// <summary>
        /// 获取库位
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> WhLocationAllAsync()
        {
            var result = await _iwos.WhLocationAllAsync();
            if (result!=null)
            {
                var date = result.Select(x => new
                {
                    storageLocationId = x.StorageLocationId,
                    storageLocationName = x.StorageLocationName,
                    warehouseId = x.WarehouseId
                });
                return this.Success(date);
            }
            else
            {
                return this.Error();
            }
        }
        /// <summary>
        /// 根据仓库ID获取库位
        /// </summary>
        /// <param name="warehouseId">仓库ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetLocationsByWarehouseId(long warehouseId)
        {
            var result = await _iwos.GetLocationsByWarehouseIdAsync(warehouseId);
            if (result != null)
            {
                var data = result.Select(x => new
                {
                    storageLocationId = x.StorageLocationId,
                    storageLocationName = x.StorageLocationName,
                    warehouseId = x.WarehouseId
                });
                return this.Success(data);
            }
            else
            {
                return this.Error();
            }
        }
        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            return View();
        }

        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        /// <summary>
        /// 删除api接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            if(await _iwos.DeleteAsync(id)>0) 
            {
                return this.Success();
            }
            else
            {
                return this.Error();
            }
        }
        
        /// <summary>
        /// 获取订单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSalesOrerAllAsync()
        {
            var result = await _iosos.GetAllWithDetailsAsync();
            // 调用新的无批次库存查询方法
            var date = result
                .Where(x => x.OrderStatus == "3"|| x.OrderStatus == "4")
                .Select(x => new
                {
                    salesOrderNo = x.SalesOrderNo,
                    orderStatus = x.OrderStatus,
                    salesDate = x.SalesDate,
                    customerName = x.CustomerName,
                    sellerShortName = x.SellerShortName,
                    sellerBy = x.SellerBy,
                    salesQuantity = x.SalesQuantity,
                    salesAmount = x.SalesAmount
                });
            return this.Success(date);
        }
        /// <summary>
        /// 获取收货人
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UserAllAsync()
        {
            var date = await _iwos.UserAll();
            var result = date.Select(x=>new
            {
                id=x.UsersId,
                name=x.UsersName,
                honeUmber = x.UsersHoneUmber
            });
            return this.Success(result);
        }

        /// <summary>
        /// 审核动作
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateAuditorComment([FromBody] Auditor date)
        {
            using var transaction = await _dbContext.Database.BeginTransactionAsync();
            if (date == null)
            {
                return Ok(new { code = 400, msg = "审核数据不能为空" });
            }

            if (date.Id <= 0)
            {
                return Ok(new { code = 400, msg = "订单ID无效" });
            }

            try
            {
                var result = await _iwos.UpdateAuditorComment(date);
                if (result > 0)
                {
                    // 如果审核通过，执行实际出库操作
                    if (date.OrderStatus == "3") // 审核通过
                    {
                        var outboundResult = await _iwos.ExecuteActualOutbound(date.Id);
                        if (outboundResult > 0)
                        {
                            await transaction.CommitAsync();
                            return Ok(new { code = 200, msg = "审核成功并完成实际出库" });
                        }
                        else
                        {
                            await transaction.RollbackAsync();
                            return Ok(new { code = 500, msg = "审核成功但实际出库执行失败" });
                        }
                    }
                    else
                    {
                        await transaction.CommitAsync();
                        return Ok(new { code = 200, msg = "审核成功" });
                    }
                }
                else
                {
                    await transaction.RollbackAsync();
                    return Ok(new { code = 404, msg = "审核失败，订单可能不存在" });
                }
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                return Ok(new { code = 500, msg = $"审核异常: {ex.Message}" });
            }
        }
        /// <summary>
        /// 状态变更
        /// </summary>
        /// <param name="status">字符串类型的状态参数如0,1,2,3.....</param>
        /// <param name="id">目标订单</param>
        /// <returns></returns>
        public async Task<IActionResult> AuditorStatus(string status, long id)
        {
            if (await _iwos.AuditorStatus(status, id) > 0)
            {
                return this.Success("状态变更成功");
            }
            else
            {
                return this.Error();
            }
        }
        /// <summary>
        /// 状态变更（启用停用）
        /// </summary>
        /// <param name="status">字符串类型的状态参数如0,1,</param>
        /// <param name="id">目标订单</param>
        /// <returns></returns>
        public async Task<IActionResult> Status(string status, long id)
        {
            if (await _iwos.Status(status, id) > 0)
            {
                return this.Success("状态变更成功");
            }
            else
            {
                return this.Error();
            }
        }
    }

    /// <summary>
    /// 审核请求模型
    /// </summary>
    public class AuditRequest
    {
        public long Id { get; set; }
        public string OrderStatus { get; set; }
        public string AuditorComment { get; set; }
        public string AuditorBy { get; set; }
        public string AuditorTime { get; set; }
    }
}